package cn.heima.heima_netty.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import static cn.heima.heima_netty.nio.c1.ByteBufferUtil.debugRead;

/**
 * @author felix
 * @date 2024/9/12 16:54
 *
 * 1. 连接成功后，将socketChannel注册到worker的selector上
 * 2. worker的selector监听读写事件，读取数据
 * 3. 调整注册事件位置，避免selector.select()无限等待
 * 4. 线程间通信,调整注册事件发生线程
 *
 * */
@Slf4j
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss ");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8089));

        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, SelectionKey.OP_ACCEPT, null);
        Worker worker = new Worker("worker-0");
        while(true){
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected:{}",sc.getRemoteAddress());
                    log.debug("before register:{}",sc.getRemoteAddress());
                    worker.register(sc);
                    log.debug("after register:{}",sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable{
        private Thread thread;
        private String name;
        private Selector selector;
        private volatile boolean start = false;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name){
            this.name = name;
        }

        // 调用此方法的是boss线程，下述run方法才是worker-0线程
        public void register(SocketChannel sc) throws IOException {
            if(!start){
                selector = Selector.open();
                thread = new Thread(this,name);
                thread.start();
                start = true;
            }

            // 仅在队列中添加了任务，并没有执行
            queue.add(()->{
                try {
                    sc.register(selector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });
            /**
             * 1. 手动唤醒selector
             * 2. 首次进入run方法中循环，queue中注册监听写任务还未执行
             * 3. 手动唤醒selector，完成注册监听写任务
             * 4. 再次进入循环时selector.select()依旧阻塞，但selector已经监听read
             * 5. read事件发生时，阻塞结束，向下运行
             */
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    Runnable task = queue.poll();
                    if (task!=null) {
                        task.run();
                    }
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isReadable()){
                            SocketChannel sc = (SocketChannel)key.channel();
                            sc.configureBlocking(false);
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            log.debug("read:{}",sc.getRemoteAddress());
                            sc.read(buffer);
                            buffer.flip();
                            debugRead(buffer);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
